"""
-------------------------------
- File_Name: login.py
- Date: 2025/2/18
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 用户接口
-------------------------------
"""
from typing import Any

from fastapi import APIRouter, Depends, Path, Body, Query, HTTPException
from app.schemas import BaseResponse, BaseResponseExtra
from app.schemas.system.users import *
from app.models.system.admin import User, Role, UserRole
from app.core.security import get_current_user,get_password_hash,verify_password
from app.utils.ormUtil import OrmCRUD
from app.utils.responseUtil import ResponseUtil
from app.core.ctx import CTX_USER

router = APIRouter(prefix="/systemManage", dependencies=[Depends(get_current_user)])
tags = ["系统用户信息"]
description = "系统用户信息相关接口"


async def delete_user(user_id: int | str):
    user_code = await User.get(id=user_id).values_list("user_code", flat=True)
    # 特殊人员禁止删除
    if user_code in ['9999']:
        raise HTTPException(status_code=401, detail="超级管理员拒绝执行")
    user_obj = await OrmCRUD(User).delete(user_id)
    if user_obj is None:
        raise HTTPException(status_code=404, detail=f"删除用户不存在【id={user_id}】")

    # 删除“用户角色”列表
    await UserRole.filter(user_id=user_id).delete()
    return user_obj


@router.post("/users", summary="新增用户信息", response_model=BaseResponse[SystemUserOut])
async def post_user(user_in: SystemUserCreate):
    """系统管理-创建用户"""
    # 更新创建人
    user_in.create_by = CTX_USER.get().user_name
    # 新的用户对象
    user_dict = await OrmCRUD(User).add(**user_in.model_dump(exclude={"user_roles"}))

    # 更新用户角色表
    # 角色id 列表
    role_list = await Role.filter(role_code__in=user_in.user_roles).values_list("id", flat=True)
    # 所有用户角色更新对象
    user_role_list = [UserRole(user_id=user_dict["id"], role_id=role) for role in role_list]
    # 批量创建
    await UserRole.bulk_create(user_role_list)

    # 返回用户角色编号
    user_dict["user_role"] = user_in.user_roles
    return ResponseUtil.success_response(data=user_dict, msg=f"创建用户【{user_dict['user_name']} | {user_dict['user_code']}】成功")


@router.delete("/users/{id}", summary="删除用户信息", response_model=BaseResponse[dict])
async def _(_id: str = Path(alias="id", description="用户id")):
    """系统管理-删除用户"""
    await delete_user(_id)
    return ResponseUtil.success_response(data={}, msg=f"删除用户【{_id}】成功")


@router.delete("/users", summary="批量删除用户信息", response_model=BaseResponse[dict])
async def _(user_ids: str = Query(..., alias="ids")):

    # ids转列表
    ids_list = user_ids.split(",")
    for id in ids_list:
        await delete_user(id)
    return ResponseUtil.success_response(data={}, msg=f"批量删除用户成功")


@router.patch("/users/{id}", summary="更新用户信息", response_model=BaseResponse[SystemUserOut])
async def update_user(
        _id: int|str = Path(alias="id", description="用户id"),
        user_update: SystemUserUpdate = Body(...)
):
    # 更新的角色id列表
    update_role_list = await Role.filter(role_code__in=user_update.user_roles).values_list("id", flat=True)
    # 当前用户角色id列表
    current_role_list = await UserRole.filter(user_id=_id).values_list("role_id", flat=True)

    # 更新者
    user_update.update_by = CTX_USER.get().user_name
    # update自动过滤无关字段
    user_dict = await OrmCRUD(User).update(data=user_update, id=_id)
    if user_dict is None:
        raise HTTPException(status_code=404, detail=f"更新用户不存在【id={_id}】")

    # 1. 先删除角色id
    del_role_list_set = list(set(current_role_list) - set(update_role_list))
    if del_role_list_set:
        await UserRole.filter(user_id=_id, role_id__in=del_role_list_set).delete()
    # 2. 再新增角色id
    add_role_list_set = list(set(update_role_list) - set(current_role_list))
    if add_role_list_set:
        add_role = [UserRole(user_id=user_dict["id"], role_id=role) for role in add_role_list_set]
        await UserRole.bulk_create(add_role)

    # 返回用户角色编码
    user_dict["userRoles"] = user_update.user_roles
    return ResponseUtil.success_response(data=user_dict, msg=f"更新用户【{user_dict['user_name']} | {user_dict['user_code']}】成功")


@router.get("/users/{id}", summary="查询某一用户信息", response_model=BaseResponse[SystemUserOut])
async def get_user(_id: int = Path(alias="id", description="用户id")):
    user_dict = await OrmCRUD(User).get_or_none(id=_id)
    if user_dict is None:
        raise HTTPException(status_code=404, detail=f"查询用户【id={_id}】不存在")
    # 更新用户角色
    role_id = await UserRole.filter(user_id=_id).values_list("role_id", flat=True)
    user_dict["userRoles"] = await Role.filter(id__in=role_id).values_list("role_code", flat=True)
    return ResponseUtil.success_response(data=user_dict, msg=f"查询用户【{user_dict['user_code']}】成功")

@router.get("/getUserList", summary="查询所有用户信息", response_model=BaseResponseExtra[SystemUserOut])
@router.get("/users", summary="查询所有用户信息", response_model=BaseResponseExtra[SystemUserOut])
async def get_user(
        current: int = Query(default=1, ge=1),
        size: int = Query(default=10, ge=1),
        user_name: str = Query("", alias="userName", description="用户名称"),
        user_code: str = Query("", alias="userCode", description="登录账号"),
        nick_name: str = Query("", alias="nickName", description="昵称"),
        user_gender: str = Query("", alias="userGender", description="性别"),
        user_phone: str = Query("", alias="userPhone", description="手机号"),
        status: str = Query("", alias="status", description="用户状态"),
        online: str = Query("", alias="online", ),
):
    total, data = await OrmCRUD(User).filter(
        current,
        size,
        order=["id"],
        user_name__icontains=user_name,
        user_code__icontains=user_code,
        nick_name__icontains=nick_name,
        user_gender__icontains=user_gender,
        user_phone__icontains=user_phone,
        status__icontains=status,
        online__icontains=online,
    )
    # 更新每个用户角色编号
    for d in data:
        # 1. 用户role_id列表: [] 或者[2, 4, 5]等更多
        role_id = await UserRole.filter(user_id=d['id']).values_list("role_id", flat=True)
        # 2. 获取用不角色代码
        role = await Role.filter(id__in=role_id).values_list("role_code", flat=True)
        d['userRoles'] = role
    return ResponseUtil.success_response_extra(total, current, size, data, msg="查询用户成功")

@router.patch("/users/updatePassword/{id}", summary="更新用户登录密码", response_model=BaseResponse[SystemUserOut])
async def update_user_password(
        _id: str | int = Path(..., alias="id", description="用户id"),
        user_update: SystemUserUpdatePwd = Body(..., description="用户新旧密码")
):
    # 验证用户id
    user_dict = await OrmCRUD(User).get_or_none(id=_id)
    if user_dict is None:
        raise HTTPException(status_code=404, detail=f"查询用户【id={_id}】不存在")
    # 验证原密码
    if not verify_password(user_update.old_password, user_dict["password"]):
        raise HTTPException(status_code=404, detail=f"旧密码不正确")
    # 更新密码
    update_new_pwd_hash = get_password_hash(user_update.new_password)
    new_user_dict = await OrmCRUD(User).update(data=SystemUserUpdateNewPwd(password=update_new_pwd_hash), id=_id)
    return ResponseUtil.success_response(data=new_user_dict, msg=f"用户【{new_user_dict['user_name']}】登录密码更新成功")